<?php
/**
 * \file captcha.php
 * \brief Catcha
 * \author Bontiv
 * \version 1.0
 * Display and use catcha.
 * \defgroup captcha Lib Captcha
 */

/* Library needed for the Captcha Error */
core_libraries::LoadLibrary('form');

/**
 * \class Captcha_Error
 * \brief Captcha validation error.
 * \ingroup exception
 * Captcha error. The code was wrong.
 * \ingroup captcha
 */
class Captcha_Error extends FormValidateError {
	function __construct()
	{
		parent::__construct(array('label' => 'Captcha', 'error' => ': The captcha value is wrong.'));
	}
}

/**
 * \class Captcha
 * \brief  Captcha library
 *
 * Catcha emulation to use Crypographp.
 * \ingroup captcha
 */
class Captcha {

	function __construct()
	{
		$cryptinstall = core_settings::Get('sitepath') . 'libexec/Captcha/cryptographp.fct.php';
		include dirname(__FILE__) . '/captcha/cryptographp.fct.php';
	}

	/// \brief Code verification
	///
	/// Verify if the $code is the correct Captcha code.
	/// \param $code the code it have to verify
	/// \return bool true if the captcha code is correct, raise \ref Captcha_Error else.
	function verify($code)
	{
		if (!chk_crypt($code))
			throw new Captcha_Error();
		return true;
	}

	/// \brief Display captcha
	///
	/// Get the captcha diplay HTML code.
	/// \return string HTML code to display.
	function display()
	{
		$buffer = ob_get_contents();
		if ($buffer !== false)
			ob_end_clean();

		ob_start();

		dsp_crypt(0,1);
		$data = ob_get_contents();
		ob_end_clean();

		if ($buffer !== false)
		{
			ob_start();
			echo $buffer;
		}

		return $data;
	}

	static function libexec($url)
	{
		$captchadir = dirname(__FILE__) . '/captcha';
		$_COOKIE['cryptcookietest'] = 1;

		if ($url == 'libexec/Captcha/images/reload.png')
		{
			header('Content-Type: image/png');
			readfile($captchadir . '/images/reload.png');
		}
		else
		{
			global  $img, $ink, $charR, $charG, $charB, $charclear, $xvariation, $charnb, $charcolorrnd, $charcolorrndlevel, $tword, $charspace;
			global $noisecolorchar, $bg, $brushsize;
			global $noisepxmin, $noisepxmax, $noiselinemin, $noiselinemax, $nbcirclemin, $nbcirclemax, $cryptwidth, $cryptheight;
			chdir($captchadir);
			include $captchadir . '/cryptographp.inc.php';
		}
	}
}
